# -*- coding: utf-8 -*-
# @Env    : v-3.5.4
# @File   : manage.py
# @Author : Kevin.Liu
# @Date   : 2019/1/7
# @Desc   : 用户管理
from os import path
from uuid import uuid4

from flask import Blueprint, redirect, url_for, flash, render_template, request

from blog.forms import LoginForm, RegisterForm
from blog.models import User, db

manage_blueprint = Blueprint("manage", __name__, template_folder=path.join(path.pardir, "templates", "manage"))


@manage_blueprint.route("/")
def index():
    return redirect(url_for("blog.home"))


@manage_blueprint.route("/login", methods=["GET", "POST"])
def login():
    """登录功能"""

    # 登录校验
    form = LoginForm()

    if form.validate_on_submit():
        flash("登录成功", category="success")
        return redirect(url_for("blog.home"))
    return render_template("login.html", form=form)


@manage_blueprint.route("/logout", methods=["GET", "POST"])
def logout():
    """退出"""

    flash("退出成功", category="success")
    return redirect(url_for("blog.home"))


@manage_blueprint.route("/register", methods=["GET", "POST"])
def register():
    """注册"""

    # 验证用户是否存在
    form = RegisterForm()

    if form.validate_on_submit():
        new_user = User(id=str(uuid4()), username=form.username.data,
                        password=form.password.data)
        db.session.add(new_user)
        db.session.commit()

        flash("注册成功，请登录", category="success")
        redirect(url_for("manage.login"))
    return render_template("register.html", form=form)
